package com.tiyo.system.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiyo.common.utils.StringUtils;
import com.tiyo.system.mapper.SysDictDataMapper;
import com.tiyo.system.mapper.SysDictTypeMapper;
import com.tiyo.system.mapper.domain.SysDictData;
import com.tiyo.system.mapper.domain.SysDictType;
import com.tiyo.system.service.SysDictService;
import com.tiyo.system.utils.DictUtils;

@Service
public class SysDictServiceImpl implements SysDictService {
	@Autowired
	SysDictDataMapper sysDictDataMapper;
	@Autowired
	SysDictTypeMapper sysDictTypeMapper;

	/**
	 * 项目启动时，初始化字典到缓存
	 */
	@PostConstruct
	public void init() {
		List<SysDictType> dictTypeList = sysDictTypeMapper.selectList(new QueryWrapper<SysDictType>());
		QueryWrapper<SysDictData> queryWrapper = null;
		for (SysDictType dictType : dictTypeList) {
			queryWrapper = new QueryWrapper<SysDictData>();
			queryWrapper.eq("dict_type", dictType.getDictType());
			queryWrapper.eq("status", "0");
			List<SysDictData> dictDatas = sysDictDataMapper.selectList(queryWrapper);
			DictUtils.setDictCache(dictType.getDictType(), dictDatas);
		}
	}

	@Override
	public String getLaber(String dictType, String dictValue) {
		QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<SysDictData>();
		queryWrapper.select("dict_label", "dict_value", "dict_type");
		queryWrapper.eq("dict_type", dictType);
		queryWrapper.eq("dict_value", dictValue);
		List<SysDictData> list = sysDictDataMapper.selectList(queryWrapper);
		if (StringUtils.isEmpty(list)) {
			return "";
		} else {
			return list.get(0).getDictLabel();
		}
	}

	@Override
	public List<SysDictType> listTypeAll() {
		QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<SysDictType>();
		return sysDictTypeMapper.selectList(queryWrapper);
	}

	@Override
	public SysDictType getType(String dictTypeId) {
		return sysDictTypeMapper.selectById(dictTypeId);
	}

	@Override
	public List<SysDictData> getData(String dictTypeId) {
		List<SysDictData> dictDatas = DictUtils.getDictCache(dictTypeId);
		if (StringUtils.isNotEmpty(dictDatas)) {
			return dictDatas;
		}
		QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<SysDictData>();
		queryWrapper.select("dict_label", "dict_value", "dict_type");
		queryWrapper.eq("dict_type", dictTypeId);
		queryWrapper.orderByAsc("dict_sort");
		dictDatas = sysDictDataMapper.selectList(queryWrapper);
		if (StringUtils.isNotEmpty(dictDatas)) {
			DictUtils.setDictCache(dictTypeId, dictDatas);
			return dictDatas;
		}
		return null;
	}

}
